package mobilesafe.guoshisp.com.xdtong;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import mobilesafe.guoshisp.com.xdtong.entity.StudentInfo;
import mobilesafe.guoshisp.com.xdtong.model.Const;
import mobilesafe.guoshisp.com.xdtong.net.HandleNetCallBack;
import mobilesafe.guoshisp.com.xdtong.net.ThreadHttpGet;
import mobilesafe.guoshisp.com.xdtong.net.ThreadHttpPost;
import mobilesafe.guoshisp.com.xdtong.util.ParseHtml;
import mobilesafe.guoshisp.com.xdtong.view.DribSearchView;

/**
 * Description:主界面
 * User: Dream_Coder(chenchen_839@126.com)
 * Date: 2015-07-19
 * Time: 00:49
 */
public class MainActivity extends Activity implements View.OnClickListener{
    private String mCookie = "";
    private String location= "";
    private StudentInfo studentInfo;
    private Button mButton;
    private TextView name;
    private TextView studentNum;
    private LinearLayout result;
    private TextView times;
    private EditText et_num;
    private String et_studentNum;
    private DribSearchView dribSearchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    /*初始化view组件*/
    public void initView() {
        mButton = (Button) findViewById(R.id.getData);
        name = (TextView) findViewById(R.id.name);
        studentNum = (TextView) findViewById(R.id.studentNum);
        times = (TextView) findViewById(R.id.times);
        et_num = (EditText) findViewById(R.id.num);
        result = (LinearLayout) findViewById(R.id.result);
        mButton.setOnClickListener(this);
    }

    /**
     * 显示toast
     * @param resId
     */
    public void showToast(int resId) {
        String msg = getResources().getString(resId);
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }
    public void showToast(String msg) {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    /**
     * 发送请求
     */
    public void sendRequest() {
        new Thread(new ThreadHttpGet(Const.BASE_URL, new HandleNetCallBack() {
            @Override
            public void OnSuccess(HttpResponse httpResponse) {
                mCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
                getData();
            }
            @Override
            public void OnFail(HttpResponse httpResponse) {
                showToast("错误码:"+httpResponse.getStatusLine().getStatusCode());
            }
        })).start();
    }

    /**
     * 获取数据
     */
    public void getData() {

        new Thread(new ThreadHttpPost(Const.LOGIN_URL,
                new String[]{mCookie, et_studentNum}, new HandleNetCallBack() {
            StringBuffer content = new StringBuffer();
            @Override
            public void OnSuccess(HttpResponse httpResponses) {
                InputStream is = null;
                try {
                    is = httpResponses.getEntity().getContent();
                    BufferedReader br =new BufferedReader(new InputStreamReader(is));
                    String line = "";
                    while((line = br.readLine()) != null) {
                        content.append(line);
                    }
                    studentInfo = ParseHtml.parseStudentInfo(content);
                    content.delete(0,content.length());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(content.toString());
                Message msg = Message.obtain();
                msg.what = Const.SUCCESS_GET_DATA;
                handler.sendMessage(msg);

            }

            @Override
            public void OnFail(HttpResponse httpResponse) {

            }
        })).start();
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.getData) {
            String num = et_num.getText().toString().trim();
            if(num.equals("")) {
                showToast("学号不能为空");
            }else {
                et_studentNum = num;
            }
            if(studentInfo != null) {
                loginOut();
            }
            sendRequest();
        }
    }
    /*退出登录*/
    public void loginOut() {
        new Thread(new ThreadHttpGet(Const.LOGINOUT_URL, new HandleNetCallBack() {
            @Override
            public void OnSuccess(HttpResponse httpResponses) {
                InputStream is = null;
                StringBuffer contents = new StringBuffer();
                try {
                    is = httpResponses.getEntity().getContent();
                    BufferedReader br =new BufferedReader(new InputStreamReader(is));
                    String line = "";
                    while((line = br.readLine()) != null) {
                        contents.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void OnFail(HttpResponse httpResponse) {
                showToast("登出失败，请重新打开使用");
            }
        })).start();
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Const.FAIL_GET_COOKIE:
                    showToast(R.string.fail_get_cookie);break;
                case Const.SUCCESS_GET_COOKIE:
                    mCookie = (String) msg.obj;break;
                case Const.FAIL_GET_DATA:
                    showToast(R.string.fail_get_data);break;
                case Const.SUCCESS_GET_DATA:
                    result.setVisibility(View.VISIBLE);
                    name.setText("姓名: "+studentInfo.getName());
                    studentNum.setText("学号: "+studentInfo.getStudentNum());
                    times.setText("有效次数: "+studentInfo.getValidTimes());
                    break;
            }
        }
    };
}
